package com.strongwell.awe.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.strongwell.awe.model.WxItem;
import com.strongwell.awe.model.WxTag;
import com.strongwell.awe.model.WxUser;
import com.strongwell.awe.service.WxTokenService;
import com.strongwell.awe.service.WxUserService;
import com.strongwell.awe.util.HttpUtils;
import com.strongwell.awe.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.strongwell.awe.util.WeixinUtil.upload;

@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    public WxTokenService wxTokenService;

    @Override
    public ResultUtil selUsers(Integer page, Integer limit) {

        String wxToken = wxTokenService.getToken().getToken();
        PageHelper.startPage(page, limit);

        List<WxUser> users = getWxUserList(wxToken);
        PageInfo<WxUser> pageInfo = new PageInfo<WxUser>(users);
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setCode(0);
        resultUtil.setCount(pageInfo.getTotal());
        resultUtil.setData(pageInfo.getList());
        return resultUtil;
    }

    @Override
    public WxUser selUserByOpenid(String openid) {
        /*Token token = new Token();
        WxTokenEntity wxTokenEntity = token.getToken("wxce015f87a6b073c6", "86988cf86b45b3a9477c2d005a6aaefa");
        String wxToken = wxTokenEntity.getToken();*/
        String wxToken = wxTokenService.getToken().getToken();

        String userInfo = getUserInfo(wxToken,openid);
        JSONObject userObject = JSON.parseObject(userInfo);
        System.out.println(userInfo);
        Integer subscribe = (Integer) userObject.get("subscribe");
        String openids = (String) userObject.get("openid");
        String nickname = (String) userObject.get("nickname");
        Integer sex = (Integer) userObject.get("sex");
        String language = (String) userObject.get("language");
        String city = (String) userObject.get("city");
        String province = (String) userObject.get("province");
        String country = (String) userObject.get("country");
        String headimgurl = (String) userObject.get("headimgurl");
        Integer subscribe_time = (Integer) userObject.get("subscribe_time");
        String remark = (String) userObject.get("remark");
        Integer groupid = (Integer) userObject.get("groupid");
        JSONArray tagid_list = (JSONArray) userObject.get("tagid_list");
        String subscribe_scene = (String) userObject.get("subscribe_scene");
        Integer qr_scene = (Integer) userObject.get("qr_scene");
        String qr_scene_str = (String) userObject.get("qr_scene_str");

        WxUser wxUser = new WxUser();
        wxUser.setSubscribe(subscribe);
        wxUser.setOpenid(openids);
        wxUser.setNickname(nickname);
        wxUser.setSex(sex);
        wxUser.setLanguage(language);
        wxUser.setCity(city);
        wxUser.setProvince(province);
        wxUser.setCountry(country);
        wxUser.setHeadimgurl(headimgurl);
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdate=format2.format(subscribe_time);

        wxUser.setSubscribeTime(Timestamp.valueOf(sdate));
        wxUser.setRemark(remark);
        wxUser.setGroupid(groupid);
        wxUser.setTagid_list(new JSONArray[]{tagid_list});
        wxUser.setSubscribe_scene(subscribe_scene);
        wxUser.setQr_scene(qr_scene);
        wxUser.setQr_scene_str(qr_scene_str);

        return wxUser;
    }

    @Override
    public String updateRemark(WxUser wxUser) {
        String wxToken = wxTokenService.getToken().getToken();
        String remark = wxUser.getRemark();
        String openid = wxUser.getOpenid();
        setRemark(openid,remark,wxToken);
        return "";
    }

    @Override
    public ResultUtil selTags(Integer page, Integer limit) {
        String wxToken = wxTokenService.getToken().getToken();
        PageHelper.startPage(page, limit);

        List<WxTag> tags = getWxTagList(wxToken);
        PageInfo<WxTag> pageInfo = new PageInfo<WxTag>(tags);
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setCode(0);
        resultUtil.setCount(pageInfo.getTotal());
        resultUtil.setData(pageInfo.getList());
        return resultUtil;
    }

    /*
    * 1 创建成功
    * -1	系统繁忙
    * 45157	标签名非法，请注意不能和其他标签重名
    * 45158	标签名长度超过30个字节
    * 45056	创建的标签数过多，请注意不能超过100个
    * -2 请求错误
    * */
    @Override
    public int addTag(String name) {
        Map<String,Object> param4 = new HashMap<String,Object>();
        Map<String,Object> param5 = new HashMap<String,Object>();
        param5.put("name", name);
        param4.put("tag", param5);

        JSONObject jsonThree = new JSONObject();
        jsonThree.putAll(param4);

        String wxToken = wxTokenService.getToken().getToken();

        //这里为请求接口的url   +号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+wxToken;
        try{
            String rs=HttpUtils.sendPostBuffer(url, jsonThree.toJSONString());
            JSONObject jsonObject = JSON.parseObject(rs);
            Integer errcode = (Integer) jsonObject.get("errcode");
            if(errcode == null){
                errcode = 1;
            }
            return errcode;
        }catch(Exception e){
            System.out.println("请求错误！");
            return -2;
        }
    }

    /*
    * 0 成功
    * -1 系统繁忙
    * 40032 每次传入的openid列表个数不能超过50个
    * 45159 非法的标签
    * 45059 有粉丝身上的标签数已经超过限制，即超过20个
    * 40003 传入非法的openid
    * 49003 传入的openid不属于此AppID
    * */
    @Override
    public int batchUsers(String userStr, Integer tagid) {
        String batchUsersList = "{\"openid_list\":["+userStr+"],\"tagid\":"+tagid+"}";

        String wxToken = wxTokenService.getToken().getToken();

        //这里为请求接口的url+号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token="+wxToken;
        try{
            String rs=HttpUtils.sendPostBuffer(url, batchUsersList);
            JSONObject jsonObject = JSON.parseObject(rs);
            Integer errcode = (Integer) jsonObject.get("errcode");
            return errcode;
        }catch(Exception e){
            System.out.println("请求错误！");
            return -2;
        }
    }

    @Override
    public ResultUtil selMaterials(String type) {
        String wxToken = wxTokenService.getToken().getToken();
        Map<String, Integer> param1 = new HashMap<String,Integer>();
        Integer count = 20;
        param1.put("count", count);
        Map<String, Integer> param2 = new HashMap<String,Integer>();
        Integer offset = 0;
        param1.put("offset", offset);
        Map<String, String> param3 = new HashMap<String,String>();
        String text3 = type;
        param3.put("type", text3);

        JSONObject jsonThree = new JSONObject();
        jsonThree.putAll(param3);
        jsonThree.putAll(param2);
        jsonThree.putAll(param1);
        System.out.println(jsonThree.toString());

        String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+wxToken;

        String rs = null;
        try {
            rs = HttpUtils.sendPostBuffer(url,jsonThree.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<WxItem> items=getItemList(rs);
        PageInfo<WxItem> pageInfo = new PageInfo<WxItem>(items);
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setCode(0);
        resultUtil.setCount(pageInfo.getTotal());
        resultUtil.setData(pageInfo.getList());
        return resultUtil;
    }

    //post
    private String getWxMaterialList(String wxToken) {
        String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+wxToken;

        try {
            String rs = HttpUtils.sendGetWithoutParams(url);
            return rs;
        } catch (Exception e) {
            System.out.println("请求错误！");
            return "false";
        }
    }

    private ResultUtil getWxItem(String type) throws Exception{
        String wxToken = wxTokenService.getToken().getToken();
        Map<String, Integer> param1 = new HashMap<String,Integer>();
        Integer count = 20;
        param1.put("count", count);
        Map<String, Integer> param2 = new HashMap<String,Integer>();
        Integer offset = 0;
        param1.put("offset", offset);
        Map<String, String> param3 = new HashMap<String,String>();
        String text3 = type;
        param3.put("type", text3);

        JSONObject jsonThree = new JSONObject();
        jsonThree.putAll(param3);
        jsonThree.putAll(param2);
        jsonThree.putAll(param1);
        System.out.println(jsonThree.toString());

        String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+wxToken;

        String rs = HttpUtils.sendPostBuffer(url,jsonThree.toJSONString());
        List<WxItem> items=getItemList(rs);
        PageInfo<WxItem> pageInfo = new PageInfo<WxItem>(items);
        ResultUtil resultUtil = new ResultUtil();
        resultUtil.setCode(0);
        resultUtil.setCount(pageInfo.getTotal());
        resultUtil.setData(pageInfo.getList());
        return resultUtil;
    }

    public List<WxItem> getItemList(String resultList) {
        String itemList=resultList;
        JSONObject jsonObject = JSON.parseObject(itemList);
        JSONArray item = (JSONArray) jsonObject.get("item");
        List<WxItem> itemArrayList = new ArrayList<>();
        if(item.size() > 0){
            for (int i = 0; i < item.size(); i++) {
                JSONObject tag = (JSONObject) item.get(i);
                String media_id = (String)tag.get("media_id");
                String name = (String) tag.get("name");
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Integer update_time = (Integer) tag.get("update_time");
                String utime=format2.format(update_time);
                String url = (String) tag.get("url");

                WxItem wxItem = new WxItem();
                wxItem.setMedia_id(media_id);
                wxItem.setUpdate_time(Timestamp.valueOf(utime));
                wxItem.setName(name);
                wxItem.setUrl(url);
                itemArrayList.add(wxItem);
            }
        }
        return itemArrayList;
    }

    /*public static void main(String[] args) {
        String url="https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=14_dpz-Spa3XN2teUE3FLaPxPeQiIBeFyMu1OR2zbS0OU_T5uVn1RDC9LxeKF9-mO4Ei38kKfPCtnq_qbUjAAvASKrcdfbKVrVykJziubInj6P7NqKhQ8rj3iqT95Cg_shLVPgzlZWeKrf43YTOXABjAAAADE";

        try {
            String rs = HttpUtils.sendGetWithoutParams(url);
            System.out.println(rs);
        } catch (Exception e) {
            System.out.println("请求错误！");
        }
    }*/

    @Override
    public String uploadFilee(File file) {
        System.out.println("进入到方法实现类");
        System.out.println(file.getName()+"-----------------balabalabala");
        String wxToken = wxTokenService.getToken().getToken();
        String result = null;
        try {
            result = upload(file,wxToken,"image");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        System.out.println(result);

        return result;
    }



    /*public static void main(String[] args) {
        String userStr = "\"oHNu65msw7QTQbWlE9dJQF9FU--4\",\"oHNu65r6FjpMU5VVnG8x80F2xcH0\"";
        Integer tagid = 100;

        String batchUsersList = "{\"openid_list\":["+userStr+"],\"tagid\":"+tagid+"}";


        //这里为请求接口的url   +号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=13_UguNTQwAdpF9851KWTuM-ktcc8aPd_3ECqez2xZDQ4ffWYqB_ML9Jn1LqbQ-7iWcbkHo4RJZ3rIQcrrsMdysT2pFv0Ijl4ZzVD4it6ScoTC9z2BmUb3ooU-XSqpFPGB8RJ0vyLvAYIjWJyLEXKRdABADQX";
        try{
            String rs=HttpUtils.sendPostBuffer(url, batchUsersList);
            JSONObject jsonObject = JSON.parseObject(rs);
            Integer errcode = (Integer) jsonObject.get("errcode");
            System.out.println(errcode);
        }catch(Exception e){
            System.out.println("请求错误！");
            System.out.println(-2);
        }

        System.out.println(batchUsersList);
    }*/

    private List<WxTag> getWxTagList(String wxToken) {
        String tagList = getTagList(wxToken);
        JSONObject jsonObject = JSON.parseObject(tagList);
        JSONArray tags = (JSONArray) jsonObject.get("tags");
        List<WxTag> tagArrayList = new ArrayList<>();
        if(tags.size() > 0){
            for (int i = 0; i < tags.size(); i++) {
                JSONObject tag = (JSONObject) tags.get(i);
                String name = (String)tag.get("name");
                Integer count = (Integer) tag.get("count");
                Integer id = (Integer) tag.get("id");

                WxTag wxTag = new WxTag();
                wxTag.setCount(count);
                wxTag.setId(id);
                wxTag.setName(name);
                tagArrayList.add(wxTag);
            }
        }
        return tagArrayList;
    }

    /*public static void main(String[] args) {
        String tagList = "{\"tags\":[{\"id\":2,\"name\":\"星标组\",\"count\":0},{\"id\":100,\"name\":\"d\",\"count\":0}]}";
        JSONObject jsonObject = JSON.parseObject(tagList);
        JSONArray tags = (JSONArray) jsonObject.get("tags");
        List<WxTag> tagArrayList = new ArrayList<>();
        if(tags.size() > 0){
            for (int i = 0; i < tags.size(); i++) {
                JSONObject tag = (JSONObject) tags.get(i);
                String name = (String)tag.get("name");
                Integer count = (Integer) tag.get("count");
                Integer id = (Integer) tag.get("id");

                WxTag wxTag = new WxTag();
                wxTag.setCount(count);
                wxTag.setId(id);
                wxTag.setName(name);
                tagArrayList.add(wxTag);
            }
        }
        System.out.println(tagArrayList);
    }*/

    private String getTagList(String wxToken) {
        String url="https://api.weixin.qq.com/cgi-bin/tags/get?access_token="+wxToken;

        try {
            String rs = HttpUtils.sendGetWithoutParams(url);
            return rs;
        } catch (Exception e) {
            System.out.println("请求错误！");
            return "false";
        }
    }

    public List<WxUser> getWxUserList(String wxToken) {

        String userList = getList(wxToken);
        JSONObject jsonObject = JSON.parseObject(userList);
        JSONObject openids = (JSONObject) jsonObject.get("data");
        JSONArray openidArray = (JSONArray) openids.get("openid");
        List<WxUser> wxUserList = new ArrayList<WxUser>();
        if (openidArray.size() > 0) {
            String userInfo = null;

            for (int i = 0; i < openidArray.size(); i++) {
                String openidss = openidArray.getString(i);
                userInfo = getUserInfo(wxToken, openidss);
                JSONObject userObject = JSON.parseObject(userInfo);
                System.out.println(userInfo);
                Integer subscribe = (Integer) userObject.get("subscribe");
                String openid = (String) userObject.get("openid");
                String nickname = (String) userObject.get("nickname");
                Integer sex = (Integer) userObject.get("sex");
                String language = (String) userObject.get("language");
                String city = (String) userObject.get("city");
                String province = (String) userObject.get("province");
                String country = (String) userObject.get("country");
                String headimgurl = (String) userObject.get("headimgurl");
                Integer subscribe_time = (Integer) userObject.get("subscribe_time");
                String remark = (String) userObject.get("remark");
                Integer groupid = (Integer) userObject.get("groupid");
                JSONArray tagid_list = (JSONArray) userObject.get("tagid_list");
                String subscribe_scene = (String) userObject.get("subscribe_scene");
                Integer qr_scene = (Integer) userObject.get("qr_scene");
                String qr_scene_str = (String) userObject.get("qr_scene_str");

                WxUser wxUser = new WxUser();
                wxUser.setSubscribe(subscribe);
                wxUser.setOpenid(openid);
                wxUser.setNickname(nickname);
                wxUser.setSex(sex);
                wxUser.setLanguage(language);
                wxUser.setCity(city);
                wxUser.setProvince(province);
                wxUser.setCountry(country);
                wxUser.setHeadimgurl(headimgurl);
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String sdate=format2.format(subscribe_time);

                wxUser.setSubscribeTime(Timestamp.valueOf(sdate));
                wxUser.setRemark(remark);
                wxUser.setGroupid(groupid);
                wxUser.setTagid_list(new JSONArray[]{tagid_list});
                wxUser.setSubscribe_scene(subscribe_scene);
                wxUser.setQr_scene(qr_scene);
                wxUser.setQr_scene_str(qr_scene_str);
                wxUserList.add(wxUser);
            }

        }
        System.out.println(wxUserList);
        return wxUserList;
    }

    public static String getUserInfo(String wxToken,String openid){
        //这里为请求接口的url   +号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+wxToken+"&openid="+openid+"&lang=zh_CN";

        try {
            String rs = HttpUtils.sendGetWithoutParams(url);
            return rs;
        } catch (Exception e) {
            System.out.println("请求错误！");
            return "false";
        }
    }

    //获取用户列表，返回用户的openID，{"total":2,
    //"count":2,
    //"data":{
    //"openid":["OPENID1","OPENID2"]},
    //"next_openid":"NEXT_OPENID"
    //}
    public static String getList(String wxToken){
        //这里为请求接口的url   +号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+wxToken;

        try {
            String rs = HttpUtils.sendGetWithoutParams(url);
            return rs;
        } catch (Exception e) {
            System.out.println("请求错误！");
            return "false";
        }
    }

    public static String setRemark(String openid,String remark,String wxToken){
        //这里为请求接口的url   +号后面的是token，这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token="+wxToken;
        Map<String, String> param1 = new HashMap<String,String>();
        String text = remark;
        param1.put("remark", text);
        Map<String, String> param2 = new HashMap<String,String>();
        String text2 = openid;
        param1.put("openid", text2);

        JSONObject jsonThree = new JSONObject();
        jsonThree.putAll(param2);
        jsonThree.putAll(param1);
        System.out.println(jsonThree.toString());
        try {
            String rs = HttpUtils.sendPostBuffer(url,jsonThree.toJSONString());
            return rs;
        } catch (Exception e) {
            System.out.println("请求错误！");
            return "false";
        }
    }
}
